// TypeScript 前端解密代码
import CryptoJS from 'crypto-js';
import { AESCryptoUtils } from './AESCryptoUtils';
export function decryptData(encryptedData: string, key: string): string {
    // 将密钥转换为 WordArray
    const keyBytes = CryptoJS.enc.Utf8.parse(key.padEnd(32, '\0').substring(0, 32));

    // 解码 Base64
    const encryptedBytes = CryptoJS.enc.Base64.parse(encryptedData);

    // 分离 IV 和密文
    const iv = CryptoJS.lib.WordArray.create(encryptedBytes.words.slice(0, 4), 16);
    const ciphertext = CryptoJS.lib.WordArray.create(encryptedBytes.words.slice(4), encryptedBytes.sigBytes - 16);

    // 解密配置
    const decryptOptions = {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    };

    // 执行解密
    const decrypted = CryptoJS.AES.decrypt(
        { ciphertext: ciphertext } as CryptoJS.lib.CipherParams,
        keyBytes,
        decryptOptions
    );

    return decrypted.toString(CryptoJS.enc.Utf8);
}

export function simpleDecrypt(encryptedData: string): string {
    // 密钥，需要与后端保持一致
    const key = 'simple_key';
    return decryptData(encryptedData, key);
}

export async function complexDecrypt(encryptedData: string): Promise<string> {
    const a = Number(encryptedData[0])
    const keyLength = Number(encryptedData.substring(1, a + 1))
    const b = Number(encryptedData[a + 1])
    const offset = Number(encryptedData.substring(a + 2, a + 2 + b))
    const c = a + 2 + b
    const d = c + offset
    const e = d + keyLength
    const key = encryptedData.substring(d, e)
    const encrypted = encryptedData.substring(c, d) + encryptedData.substring(e)
    /*console.log(keyLength)
    console.log(offset)
    console.log(key)
    console.log(encrypted)
    console.log(encryptedData)*/
    //return decryptData(encrypted, key)
    const result = await AESCryptoUtils.decryptData(encrypted, key)
    if (result.success) {
        return result.data || Promise.reject("未知错误")
    } else {
        return Promise.reject(result.error)
    }
}

